<!--
  * 函数表达式计算
  *
  * @Author:    zzx
  * @Date:      2025-08-05 10:54:11
  * @Copyright  zzx
-->
<template>
  <a-modal
      :title="'选择方法计算米重'"
      :width="800"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="form" :label-col="{ span: 5 }" :rules="formRules">
      <a-form-item label="米重分类" name="funcId">
<!--        <ExpressionSelect ref="expressionSelect" placeholder="米重分类" width="100%" v-model:value="form.funcId" />-->
        <a-select
            v-model:value="selectFuncId"
            :style="`width: ${width}`"
            :placeholder="selectProps.placeholder"
            :showSearch="true"
            :allowClear="true"
            :size="size"
            @change="onChange"
        >
          <a-select-option v-for="item in expressionList" :key="item.funcId" :value="item.funcId">
            {{ item.funcName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item v-for="item in form.fields" :label="item.funcKey + '（mm）'" :key="item.funcKey">
        <a-input-number style="width: 100%" v-model:value="item.funcValue" :placeholder="item.funcDes" />
      </a-form-item>

    </a-form>
    <a-alert v-if="form.fields.length >0 && selectValue.remark != null" :message="selectValue.remark" type="info" show-icon />
    <div v-if="form.fields.length > 0 && resultValue != ''"  style="margin-top: 20px">
      结果：<a-button @click="copyResult" >{{resultValue}}</a-button>
    </div>
    <template #footer>
      <a-space>
        <a-button type="primary" danger @click="queryExpressionList">刷新列表</a-button>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="calculateForm">计算</a-button>
      </a-space>
    </template>
  </a-modal>

</template>

<script setup>
  import {reactive, ref, nextTick, onMounted, watch} from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { funcExpressionApi } from '/@/api/business/expression/func-expression-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import BooleanSelect from '/@/components/framework/boolean-select/index.vue';
  import CategoryTree from "/@/components/business/category-tree-select/index.vue";
  import ExpressionSelect from './func-expression-select.vue';

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['']);
  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);
  function show() {
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true;
    selectValue = {}
    nextTick(() => {
      formRef.value.clearValidate();
      selectFuncId.value = null;
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }
  // 组件ref
  const formRef = ref();

  const formDefault = {
    funcId: undefined, //方法ID
    fields: [],
  };

  const formRules = reactive({

  })

  const expressionSelect = ref();

  let form = reactive({ ...formDefault });

  const selectProps = defineProps({
    value: [Number, Array],
    placeholder: {
      type: String,
      default: '请选择',
    },
    width: {
      type: String,
      default: '100%',
    },
    size: {
      type: String,
      default: 'default',
    },
    // 角色ID，可为空
    funcName: {
      type: String,
      default: null,
    },
    // 禁用标识
    disabledFlag: {
      type: Number,
      default: 0,
    },
  });

  const expressionList = ref([])
  async function queryExpressionList() {
    try {
      let params = {
        pageNum: 1,
        pageSize: 1,
      };
      if (null != selectProps.disabledFlag) {
        params.disabledFlag = selectProps.disabledFlag;
      }
      if (null != selectProps.funcName) {
        params.funcName = selectProps.funcName;
      }
      let resp = await funcExpressionApi.queryAll(params);
      expressionList.value = resp.data;
    } catch (e) {
      smartSentry.captureError(e);
    }
  }
  onMounted(queryExpressionList);
  const selectFuncId = ref(selectProps.value);

  watch(
      () => selectProps.value,
      (newValue) => {
        selectFuncId.value = newValue;
      }
  );

  let selectValue = {}
  function onChange(value) {
    selectValue = expressionList.value.find(item => item.funcId === value)
    form.fields = selectValue.list
    for (let i = 0; i < selectValue.list.length; i++) {
      let key = selectValue.list[i].funcKey
      formRules[key] = [{ required: true, message: '字段不能为空' }]
    }
    resultValue.value = ''
  }

  // ------------------------ 计算数据 ------------------------
  let resultValue = ref()
  async function calculateForm() {
    try {
      await formRef.value.validateFields();
      await calculate();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }


  // 新建、编辑API
  async function calculate() {
    // SmartLoading.show();
    try {
      let data = selectValue
      data["list"] = form.fields
      resultValue.value = (await funcExpressionApi.calculate(selectValue)).data
      console.log("=======   resultValue   " + JSON.stringify(resultValue.value))
    } catch (err) {
      smartSentry.captureError(err);
      message.error("计算失败,请联系管理员");
    } finally {
      // SmartLoading.hide();
    }
  }

  function copyResult() {
    navigator.clipboard.writeText(resultValue.value+"")
        .then(() => {
          console.log('Text copied to clipboard');
          message.success("复制成功");
        })
        .catch((error) => {
          console.error('Failed to copy text: ', error);
          message.error("操作失败");
        });
  }

  defineExpose({
    show,
  });
</script>
